local mc = require "multicast"
local skynet = require "skynet"
local packdeal = require "packdeal"
local send_package = packdeal.send_package

local bc_channel = nil

CHAT = {} 

CHAT.WORLD_BOARDCAST = 1

-- 注册广播频道
local function register_boardcast(user,type)
    local channel = skynet.call("BOARDCAST", "lua", "register", type)

    bc_channel = mc.new {
        channel = channel ,
        dispatch = function (channel, source, ...)
            skynet.error(string.format("[CHAT] 收到消息: %s",channel), ...)
            local func = CHAT.BOARDCAST_MAP[type] 
            if func then
                func(user,...)
            end
        end
    }
    bc_channel:subscribe()
    skynet.error("[CHAT] 订阅频道: ", user.account, user:get_uid(), bc_channel)
end

function CHAT.init_chat(user)
	skynet.fork(function()
        -- 注册世界聊天广播
        register_boardcast(user,1)
    end)
end

function CHAT.destory(user)
    bc_channel:unsubscribe()
end

-- 发布一个广播
-- 广播可以作为全局的通知渠道
-- 不保证顺序，只通知在线的用户
function CHAT.add_boardcast(user,type,...)
    local ret = skynet.call("BOARDCAST", "lua", "boardcast", type, ...)
    if ret ~= true then
        skynet.error(string.format("[CHAT] add_boardcast fail, type:%d", type))
    end
    return ret
end

function CHAT.on_send_world_chat(user,data)
    local msg = data.msg
    if not msg then
        skynet.error(string.format("[CHAT] on_send_world_chat error, msg nil, uid:%d", user:get_uid()))
        return
    end
    CHAT.send_world_chat(user,msg)
end

-- 发送世界聊天
function CHAT.send_world_chat(user,...)
    local ret = CHAT.add_boardcast(user, 1, user:get_name(), ...)
end

-- 接收世界聊天信息
function CHAT.on_world_chat(user,...)
    local name,msg = ...
    local packet = { cmd = NetCmd.S2C_WORLD_CAHT, name = name, msg=msg }
    send_package(user.fd_,packet)
end

CHAT.BOARDCAST_MAP = {
    [1] = CHAT.on_world_chat,
}

return CHAT
